package com.androidme.app.framework.util;

import android.util.Log;
import com.androidme.app.framework.base.AndroidMeException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.*;

public class HttpUtils {

    public static boolean download(File file, String uri) throws IOException, AndroidMeException {
        boolean flag = false;
        file.getParentFile().mkdirs();
        File tmpFile = new File(file.getAbsolutePath() + ".tmp");
        InputStream is = null;
        BufferedOutputStream bos = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                tmpFile.createNewFile();
                is = httpResponse.getEntity().getContent();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
                byte[] buffer = new byte[4096];
                int i = is.read(buffer);
                while (i != -1) {
                    bos.write(buffer, 0, i);
                    i = is.read(buffer);
                }
                tmpFile.renameTo(file);
                flag = true;
            } else {
                Log.e(HttpUtils.class.getName(), "Http Error: StatusCode=" + statusCode);
                throw new AndroidMeException(statusCode);
            }
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (is != null) {
                is.close();
            }
        }
        return flag;
    }

}

